#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK

# Copyright 2012-2013, Andrey Kislyuk and argcomplete contributors.
# Licensed under the Apache License. See https://github.com/kislyuk/argcomplete for more info.

'''
Activate the generic bash-completion script for the argcomplete module.
'''

import os, sys, argparse, argcomplete, shutil, fileinput

parser = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

dest_opt = parser.add_argument("--dest", help="Specify the bash completion modules directory to install into", default="/etc/bash_completion.d")
parser.add_argument("--user", help="Install into user directory (~/.bash_completion.d/)", action='store_true')
parser.add_argument("--no-defaults", dest="use_defaults", action="store_false", default=True,
    help="When no matches are generated, do not fallback to readline\'s default completion")
parser.add_argument("--complete-arguments", nargs=argparse.REMAINDER,
    help="arguments to call complete with; use of this option discards default options")
argcomplete.autocomplete(parser)
args = parser.parse_args()

if args.user:
    args.dest = os.path.expanduser("~/.bash_completion.d/")
    if not os.path.exists(args.dest):
        try:
            os.mkdir(args.dest)
        except Exception as e:
            parser.error("Path {d} does not exist and could not be created: {e}".format(d=args.dest, e=e))
elif not os.path.exists(args.dest) and args.dest != '-':
    parser.error("Path {d} does not exist".format(d=args.dest))

activator = os.path.join(os.path.dirname(argcomplete.__file__), 'bash_completion.d', 'python-argcomplete.sh')

if args.complete_arguments is None:
    complete_options = '-o nospace -o default -o bashdefault' if args.use_defaults else '-o nospace -o bashdefault'
else:
    complete_options = " ".join(args.complete_arguments)
complete_call = "complete{} -D -F _python_argcomplete_global".format(" " + complete_options if complete_options else "")
def replaceCompleteCall(line):
    if line.startswith("complete") and "_python_argcomplete_global" in line:
        return complete_call+('\n' if line.endswith('\n') else '')
    else:
        return line

if args.dest == '-':
    for l in open(activator):
        sys.stdout.write(replaceCompleteCall(l))
else:
    dest = os.path.join(args.dest, "python-argcomplete.sh")

    sys.stdout.write("Installing bash completion script " + dest)
    if not args.use_defaults:
        sys.stdout.write(" without -o default")
    elif args.complete_arguments:
        sys.stdout.write(" with options: " + complete_options)
    sys.stdout.write("\n")

    try:
        shutil.copy(activator, dest)
        if not args.complete_arguments is None or not args.use_defaults:
            for l in fileinput.input(dest, inplace=True):
                # fileinput with inplace=True redirects stdout to the edited file
                sys.stdout.write(replaceCompleteCall(l))
    except Exception as e:
        err = str(e)
        if args.dest == dest_opt.default:
            err += "\nPlease try --user to install into a user directory, or --dest to specify the bash completion modules directory"
        parser.error(err)
